<template>
	<view class="star-rating">
		<view v-for="(_, index) in maxStars" :key="index" class="star-item"
			:style="size ? { width: size + 'px', height: size + 'px' } : {}">
			<!-- 背景图 -->
			<image :src="getStarImage(index)" class="star-bg" mode="aspectFit" />

			<!-- 左半 -->
			<view class="star-touch left" @tap.stop="handleClick(index, 0.5)" />

			<!-- 右整 -->
			<view class="star-touch right" @tap.stop="handleClick(index, 1)" />
		</view>
	</view>
</template>

<script setup lang="ts">
	const props = defineProps<{
		modelValue : number
		max ?: number
		size ?: number
		readonly ?: boolean
	}>()

	const emit = defineEmits(['update:modelValue', 'change'])

	const maxStars = props.max ?? 5
	const size = props.size ?? 20

	// 点击逻辑：如果重复点相同位置，则清空当前及后面星
	function handleClick(index : number, step : 0.5 | 1) {
		if (props.readonly) return

		const clickedValue = index + step

		if (Math.abs(props.modelValue - clickedValue) < 0.01) {
			// 如果点的是当前值，则截断为前一颗
			emit('update:modelValue', index)
		} else {
			emit('update:modelValue', clickedValue)
		}
		emit('change', clickedValue)
		console.log("选择的值 = ", clickedValue);
	}

	function getStarImage(index : number) : string {
		const diff = props.modelValue - index
		if (diff >= 1) return '/static/image/comment/star_filled.png'
		if (diff >= 0.5) return '/static/image/comment/star_half.png'
		return '/static/image/comment/star_empty.png'
	}
</script>

<style scoped>
	.star-rating {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.star-item {
		position: relative;
		margin-right: 5px;
	}

	.star-bg {
		width: 100%;
		height: 100%;
		display: block;
	}

	.star-touch {
		position: absolute;
		top: 0;
		bottom: 0;
		width: 50%;
	}

	.star-touch.left {
		left: 0;
	}

	.star-touch.right {
		right: 0;
	}
</style>